package filters

import (
	"github.com/dgrijalva/jwt-go"
	"time"
	"github.com/astaxie/beego/logs"
	"fmt"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/context"
	"net/http"
	"strconv"
)

var (
	key []byte = []byte (beego.AppConfig.String("JWT_SECRET"))
)
var userId int64

// 产生json web token
func GenToken() string {
	claims := &jwt.StandardClaims{
		NotBefore: int64(time.Now().Unix()),
		ExpiresAt: int64(time.Now().Unix() + 1000),
		Issuer:    "hzwy23",
	}

	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	ss, err := token.SignedString(key)
	if err != nil {
		logs.Error(err)
		return ""
	}
	return ss
}

// 校验token是否有效
func CheckToken(tokenString string, ctx *context.Context) bool {

	if (tokenString[0:7] == "Bearer ") {
		end := len(tokenString)
		tokenString = tokenString[7:end]
	}

	jtoken, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
		// Don't forget to validate the alg is what you expect:
		if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
			return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
		}

		// hmacSampleSecret is a []byte containing your secret, e.g. []byte("my_secret_key")
		return key, nil
	})

	if err != nil {
		logs.Debug(err)

	}

	if claims, ok := jtoken.Claims.(jwt.MapClaims); ok && jtoken.Valid {
		userId := int(claims["sub"].(float64))
		ctx.Input.SetParam("jwtUserId", strconv.Itoa(userId))//设置request中的参数
		return true
	} else {
		logs.Error(err)
		return false
	}
}

//过滤器
func FilterToken() {

	beego.InsertFilter("/api/*", beego.BeforeRouter, func(ctx *context.Context) {
		token := ctx.Request.Header.Get("Authorization")
		if token == "" {
			token = ctx.Input.Query("token")
		}
		if (token == "") {
			http.Error(ctx.ResponseWriter, "auth fail", 200)
			return
		}

		if !CheckToken(token, ctx) {
			http.Error(ctx.ResponseWriter, "auth fail", 200)
			return
		}
	})
}
